package com.cloud.platform.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SortUtil {
	
	public static final int ASC = 0;
	public static final int DESC = 1;

	/**
	 * sort array datas
	 * 
	 * @param datas
	 * @param position
	 * @param type
	 * @param rules
	 * @return
	 */
	public static List<Object[]> sortArray(List<Object[]> datas, int position,
			int type, List rules) {
		
		if(datas == null || datas.isEmpty()) {
			return new ArrayList();
		}
		
		// get sort keys and its' index map
		int count = 0;
		Object[] keys = new Object[datas.size()];
		Map<Object, Integer> indexMap = new HashMap();
		
		for(Object[] arr : datas) {
			keys[count] = arr[position];
			indexMap.put(arr[position], count);
			
			count++;
		}
		
		// sort keys
		sort(keys, rules);
		
		// re-combine list datas
		int index = 0;
		List<Object[]> result = new ArrayList();
		
		for(Object o : keys) {
			index = indexMap.get(o);
			result.add(datas.get(index));
		}
		
		return result;
	}
	
	/**
	 * sort method
	 * 
	 * @param keys
	 * @param rules
	 */
	private static void sort(Object[] keys, final List rules) {
		
		// default sort
		if(rules == null) {
			Arrays.sort(keys);
		}
		// custom sort
		else {
			Arrays.sort(keys, new Comparator() {
				
				public int compare(Object src, Object dest) {
					
					int srcIndex = rules.indexOf(src.toString());
					int destIndex = rules.indexOf(dest.toString());
					
					return srcIndex - destIndex;
				}
			});
		}
	}
	
	public static void main(String[] args) {
		List<Object[]> result = new ArrayList();
		result.add(new Object[] {"1", 1});
		result.add(new Object[] {"3", 3});
		result.add(new Object[] {"5", 5});
		result.add(new Object[] {"2", 2});
		result.add(new Object[] {"4", 4});
		
		List rules = new ArrayList();
		
		rules.add("1");
		rules.add("2");
		rules.add("3");
		rules.add("4");
		rules.add("5");
		
		result = sortArray(result, 1, 1, rules);
		
		for(Object[] o : result) {
			System.out.println(o[0]);
		}
	}
}
